package com.zryc.controller;

import com.zryc.service.OrderService;
import com.zryc.shop.entity.Order;
import com.zryc.shop.entity.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

//@RestController
@RequestMapping(path ="/order",method = {RequestMethod.GET,RequestMethod.POST})
@Slf4j
public class OrderController {
    @Autowired
    private OrderService orderService;
    //自动装配之前注入的RestTemplate实例
    @Autowired
    private RestTemplate restTemplate;
    //自动注入一个服务发现的客户端
    @Autowired
    private DiscoveryClient discoveryClient;
    private  String productServiceUrl;
    //商品服务中使用商品id查找商品信息
//    private String productServiceUrl="http://localhost:8081/product/";

    @RequestMapping("/prod/{pid}")
    public Map<String,Object> order(@PathVariable("pid") Integer pid){
        //serviceId就是Nacos可视化管理界面可用服务中查到的服务名称
//        ServiceInstance serviceInstance=discoveryClient.getInstances("shop-product").get(0);
//        String ip=serviceInstance.getHost();
//        int port=serviceInstance.getPort();
        log.info(">>当前用户正在完成商品下单，商品id"+pid);
        log.info(">>调用商品服务的接口查询完整商品信息！");
//        String serviceId="shop-product";
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceId);
//        int index =new Random().nextInt(serviceInstances.size());
//        String ip = serviceInstances.get(index).getHost();
//        int port=serviceInstances.get(index).getPort();
//        productServiceUrl="http://"+ip+":"+port+"/product/";
//        log.info("端口"+port);
        //借助Ribbon负载均衡
        String serviceId="shop-product";
        productServiceUrl="http://"+serviceId+"/product/";

        Product product= restTemplate.getForObject(productServiceUrl+pid,Product.class);
        log.info("开始生成订单");
        Order order=new Order();
        //系统中还没有用户数据，所以用户信息写死
        order.setUid(1);
        order.setUsername("测试用户1");
        //设置当前订单的商品INFO
        order.setPid(pid);
        order.setPname(product.getPname());
        order.setPprice(product.getPprice());
        order.setNumber(1);//购买数量
        log.info(">>调用服务层完成订单的信息存储");
        orderService.save(order);
        log.info(">>下单成功");
        Map result=new HashMap();
        result.put("PRODUCT_INFO",product);
        result.put("ORDER_INFO",order);
        return result;
    }












}
